import db from '@/utils/localstorage'
import axios from 'axios'
import request from '@/utils/request'
import { getRemoteUrlParam, getReqParamData } from '@/utils/hyurl'
import { getCheckRecordKeyStr } from './hyrecord'
import { getNewCommonUrlParam } from './hyurl'

export function getToken() {
  return db.get('ACCESS_TOKEN', '')
}

export function getRefreshToken() {
  return db.get('REFRESH_TOKEN', '')
}

export function getExpireTime() {
  return db.get('EXPIRE_TIME', 0)
}

export function getRouteTokenExpireTime() {
  return db.get('ROUTE_TOKEN_EXPIRE_TIME', 0)
}

export function getRouteToken() {
  return db.get('ROUTE_TOKEN', '')
}

export function removeRouteToken() {
  return db.remove('ROUTE_TOKEN')
}
export async function asyncSubmitDealReq(parameter) {
  const url = submitDealReqUrl(parameter)
  console.info('getBaseSubmit', parameter)
  const newurl = '/autodeal' + url
  return await request.postJson(newurl, parameter)
}

export function postSubmitReq(parameter) {
  console.info('getBaseSubmit', parameter)
  const newurl = '/autodeal' + parameter.url
  return request.postJson(newurl, parameter)
}
export function submitDealReqUrl(parameter) {
  let url = ''
  if (parameter.url === 'empty') {
    url = '/run/ctr/empty'
  } else {
    if (parameter.S_PAGE_ID !== undefined && parameter.S_PAGE_ID !== '') {
      if (parameter.url === null || undefined === parameter.url) {
        url = '/run/ctr/submitJson/' + parameter.S_PARTITION + '/' + parameter.S_PAGE_ID + '/' + parameter.S_PAGE_VER
      } else {
        if (parameter.S_PAGE_ID !== null && parameter.url !== null) {
          if (parameter.url.endsWith('/')) {
            url = parameter.url + parameter.S_PARTITION + '/' + parameter.S_PAGE_ID + '/' + parameter.S_PAGE_VER
          } else {
            url = parameter.url + '/' + parameter.S_PARTITION + '/' + parameter.S_PAGE_ID + '/' + parameter.S_PAGE_VER
          }
        } else {
          url = parameter.url
        }
      }
    } else {
      url = parameter.url
    }
  }
  if (url === undefined || url === 'empty') {
    url = '/run/ctr/empty'
  }
  return url
}

export function submitDealReq(parameter) {
  const url = submitDealReqUrl(parameter)
  let timeout = 30000
  if (parameter.timeout) {
    timeout = parameter.timeout
  }

  console.info('getBaseSubmit', parameter)
  // const newurl = '/autocode' + url
  const newurl = '/autodeal' + url
  return request.postJson(newurl, parameter)
}
export function getUIUrl(parameter) {
  const url = '/system/ui/ui/' + parameter.S_PARTITION + '/' + parameter.S_PAGE_ID + '/' + parameter.S_PAGE_VER
  return url
}

export function loadUIMethod(parameter) {
  const url = '/autoui/ui/ctr/initComonUIData/' + parameter.S_PARTITION + '/' + parameter.S_PAGE_ID + '/' + parameter.S_PAGE_VER
  return request.postJson(url, parameter)
}
export function initSessionFormDataMethod(parameter) {
  const url = '/autoui/ui/ctr/initSessionFormData'
  return request.postJson(url, parameter)
}

export function initSessionUIDataMethod(parameter) {
  const url = '/autoui/ui/ctr/initSessionUIData'
  return request.postJson(url, parameter)
}
export function loadInitAppUIDataMethod(parameter) {
  const url = '/autoui/ui/ctr/initAppUIData/' + parameter.S_PARTITION + '/' + parameter.S_PAGE_ID + '/' + parameter.S_PAGE_VER
  // const url = '/autoui/ui/ctr/initAppUIData'
  return request.postJson(url, parameter)
}

export function loadInitDataMethod(parameter) {
  return submitDealReq(parameter)
}

export function getThisObjCommonDealParam(thisObj, loadParam, globalData, rowData, urlParamKey) {
  return getReqParamData(thisObj, globalData, urlParamKey)
}

/**
 * 获取通用赋值
 * @param thisObj 当前对象
 * @param globalData 所有参数
 * @param rowData 对象数据
 * @param refSetVal 设置参数对象
 * @param 返回改参数对象值
 */
export function getThisObjCommonSetVal(thisObj, globalData, rowData, refSetVal) {
  // 先处理是否有高级配置
  const objEl = refSetVal.objEl
  if (objEl !== undefined) {
    if (!evalEl(objEl, globalData.globalParam)) {
      return null
    }
  }
  const valKey = refSetVal.val
  const defFormat = refSetVal.defFormat
  let val
  let tmpVal = ''
  if (undefined !== defFormat && defFormat !== null) {
    // 以高级配置为准
    val = getDefFormatVal(defFormat, globalData.globalParam)
  } else if (undefined === valKey) {
    val = getRefSetValDefVal(tmpVal, refSetVal)
  } else {
    const valDataSet = refSetVal.valDataSet
    if (valDataSet === 'tableSelectedRow' || refSetVal.valObj === 4) {
      tmpVal = getSelectRowVal(globalData, rowData, valKey)
    } else if (valDataSet === 'initReturnSetListData') {
      tmpVal = getSelectRowVal(globalData, rowData, valKey)
    } else if (valDataSet === 'clickRow') {
      tmpVal = getClickRowVal(globalData, valKey)
    } else if (valDataSet === 'openParam') {
      tmpVal = getOpenParamVal(globalData, valKey)
    } else if (valDataSet === 'formModel') {
      tmpVal = getFormModelVal(globalData, valKey)
    } else {
      tmpVal = getGlobalParamVal(globalData, valKey)
      if (undefined === tmpVal || tmpVal === '') {
        tmpVal = getSelectRowVal(globalData, rowData, valKey)
      }
    }
    if (undefined === tmpVal || tmpVal === '' || tmpVal === null) {
      val = getRefSetValDefVal(tmpVal, refSetVal)
    } else {
      val = tmpVal
    }
  }
  if (refSetVal.valObj === 5) {
    if (refSetVal.valIdx !== undefined) {
      if (val instanceof Array) {
        if (val.length > refSetVal.valIdx) {
          return val[refSetVal.valIdx]
        }
        return undefined
      }
      return undefined
    }
  }
  return val
}

export function getRefSetValDefVal(tmpVal, refSetVal) {
  if (undefined !== refSetVal.defVal) {
    tmpVal = refSetVal.defVal
    if (undefined !== refSetVal.valType && refSetVal.valType === 1) {
      // 配置整数类型
      return Number(tmpVal)
    } else {
      return tmpVal
    }
  }
  return tmpVal
}
/**
 * 获取click row变量值
 * @param globalData
 * @param valKey
 * @returns {*}
 */
export function getClickRowVal(globalData, valKey) {
  let tmpVal
  if (globalData.clickRow !== undefined && globalData.clickRow !== undefined) {
    tmpVal = globalData.clickRow[valKey]
  }
  if (tmpVal === undefined && globalData.formModel !== undefined) {
    tmpVal = globalData.formModel[valKey]
  }

  if (tmpVal === undefined && globalData.openParam !== undefined) {
    tmpVal = globalData.openParam[valKey]
  }

  if (tmpVal === undefined && globalData.globalParam !== undefined) {
    tmpVal = globalData.globalParam[valKey]
  }
  return tmpVal
}

/**
 * 获取global param变量值
 * @param globalData
 * @param valKey
 * @returns {*}
 */
export function getGlobalParamVal(globalData, valKey) {
  let tmpVal
  if (tmpVal === undefined && globalData.globalParam !== undefined) {
    tmpVal = globalData.globalParam[valKey]
  }
  if ((tmpVal === undefined) && globalData.clickRow !== undefined) {
    tmpVal = globalData.clickRow[valKey]
  }
  if ((tmpVal === undefined) && globalData.formModel !== undefined) {
    tmpVal = globalData.formModel[valKey]
  }
  if ((tmpVal === undefined) && globalData.openParam !== undefined) {
    tmpVal = globalData.openParam[valKey]
  }
  if ((tmpVal === undefined) && globalData.initData !== undefined) {
    tmpVal = globalData.initData[valKey]
  }
  return tmpVal
}

/**
 * 获取open param变量值
 * @param globalData
 * @param valKey
 * @returns {*}
 */
export function getOpenParamVal(globalData, valKey) {
  let tmpVal
  if (tmpVal === undefined && globalData.openParam !== undefined) {
    tmpVal = globalData.openParam[valKey]
  }
  if ((tmpVal === undefined) && globalData.clickRow !== undefined) {
    tmpVal = globalData.clickRow[valKey]
  }
  if ((tmpVal === undefined) && globalData.globalParam !== undefined) {
    tmpVal = globalData.globalParam[valKey]
  }
  if ((tmpVal === undefined) && globalData.formModel !== undefined) {
    tmpVal = globalData.formModel[valKey]
  }
  if ((tmpVal === undefined) && globalData.initData !== undefined) {
    tmpVal = globalData.initData[valKey]
  }
  return tmpVal
}
/**
 * 获取open param变量值
 * @param globalData
 * @param valKey
 * @returns {*}
 */
export function getFormModelVal(globalData, valKey) {
  let tmpVal
  // 会导致编辑重置为空时，无法修改值
  if (globalData.initData !== undefined) {
    tmpVal = globalData.initData[valKey]
  }
  if (globalData.formModel !== undefined) {
    tmpVal = globalData.formModel[valKey]
  }
  if ((tmpVal === undefined) && globalData.globalParam !== undefined) {
    tmpVal = globalData.globalParam[valKey]
  }
  if ((tmpVal === undefined) && globalData.openParam !== undefined) {
    tmpVal = globalData.openParam[valKey]
  }

  return tmpVal
}
/**
 * 获取open param变量值
 * @param globalData
 * @param rowData
 * @param valKey
 * @returns {*}
 */
export function getSelectRowVal(globalData, rowData, valKey) {
  let tmpVal
  if (rowData !== undefined) {
    tmpVal = rowData[valKey]
  }
  if (tmpVal === undefined && globalData.clickRow !== undefined) {
    tmpVal = globalData.clickRow[valKey]
  }
  if (tmpVal === undefined && globalData.globalParam !== undefined) {
    tmpVal = globalData.globalParam[valKey]
  }
  if (tmpVal === undefined && globalData.openParam !== undefined) {
    tmpVal = globalData.openParam[valKey]
  }
  if (tmpVal === undefined && globalData.formModel !== undefined) {
    tmpVal = globalData.formModel[valKey]
  }
  return tmpVal
}
export function getDefFormatVal(defFormat, defRecord) {
  const re = /(?<=)(\$\w+)(?=)/g
  const res = defFormat.replace(re, m => defRecord[m.substr(1)])
  return res
}

export function setFormObjValue(thisObj, formObj, record) {
  if (record === {} || undefined === record) {
    return
  }
  thisObj.$nextTick(() => {
    const searchFormVal = formObj
    const setVal = {}
    for (const key in searchFormVal) {
      if (undefined !== record[key]) {
        setVal[key] = record[key]
      }
    }
    formObj = Object.assign({}, formObj, setVal)
  })
}

export function getRowsFieldValue(selectionRows, field) {
  let val = null
  let idx = 0
  for (const i in selectionRows) {
    const row = selectionRows[i]
    const tempVal = row[field]
    if (undefined === tempVal || tempVal === '') {
      continue
    } else {
      if (idx > 0) {
        val = val + ','
        val = val + tempVal
      } else {
        val = tempVal
      }

      idx++
    }
  }
  return val
}

export function getRefSetValObj(selectionRows, refSetVal) {
  const record = {}
  for (const i in refSetVal) {
    const param = refSetVal[i]
    const openField = param.key
    record[openField] = getRowsFieldValue(selectionRows, openField)
  }
  return record
}

export function getQuickSetLocalFormData(selectionRows, globalData, formItem, _thisObj) {
  const tableId = _thisObj.showTableTplKey
  // const tmpGlobalData = _thisObj.$refs[tableId].globalData
  // let tmpData = getCheckRecordKeyStr(selectionRows)
  // 设置本地临时表单数据
  // const extendParam = Object.assign({}, this.searchFormParam, this.openParam, this.localParam, this.nowRow, this.uiPageUrl)
  // const record = getQuickSetLocalFormData(selectionRows, tmpGlobalData, formItem, _thisObj)
  _thisObj.$refs[tableId].setTableSearchForm(getCheckRecordKeyStr(selectionRows))
}

export function evalOpenFnKey(thisObj, openFnKey) {
  if (openFnKey === undefined) {
    return true
  } else {
    if (thisObj.initSrcObj.initSrcLabel === openFnKey) {
      return true
    }
  }
  return false
}

export function getEvaltriggerReturnObj(thisObj, triggerReturnArray) {
  let defTriggerReturn = null
  for (const i in triggerReturnArray) {
    const triggerReturn = triggerReturnArray[i]
    if (triggerReturn.openFnKey === undefined) {
      defTriggerReturn = triggerReturn
    } else {
      const evalFlag = evalOpenFnKey(thisObj, triggerReturn.openFnKey)
      if (evalFlag) {
        return triggerReturn
      }
    }
  }
  return defTriggerReturn
}
export function triggerRefOpenReturn(selectRows, formItem, _thisObj) {
  if (formItem.model !== undefined) {
    _thisObj.initReturnSetFormData[formItem.model] = selectRows
  }
  // const tableId = formItem.tableId
  // const tplObj = getTplKeyObj(_thisObj, tableId)
  // tplObj.setInitReturnSetFormData(this.initReturnSetFormData)
  const refOpen = formItem.refOpen
  if (undefined !== refOpen) {
    const triggerRefOpenData = refOpen.triggerRefOpenData
    const triggerReturnArray = triggerRefOpenData.triggerReturn
    const triggerReturn = getEvaltriggerReturnObj(_thisObj, triggerReturnArray)
    let refReturnFn = 'returnQuickSetLocalFormData'
    if (triggerReturn !== null) {
      refReturnFn = triggerReturn.refReturnFn
    }
    // for (const i in triggerReturnArray) {
    //   const triggerReturn = triggerReturnArray[i]
    if (undefined === refReturnFn || refReturnFn === '') {
      refReturnFn = 'returnQuickSetLocalFormData'
      console.log('回调函数未配置，执行默认表单设置returnQuickSetLocalFormData:')
    } else if (refReturnFn === 'returnQuickSubmitRemoteData') {
      if (formItem.key !== undefined) {
        _thisObj.initReturnSetListData[triggerReturn.returnUrlKey] = selectRows
      }
    }
    formItem.refOpen.triggerRefOpenData.activeTriggerReturn = triggerReturn
    _thisObj[refReturnFn](selectRows, formItem)
    // }
  } else {
    console.log('returnQuickSelectRows 配置数据异常.')
  }
}

export function getQuickSubmitRemoteData(returnItem, globalData, formItem, _thisObj) {
  const refOpen = formItem.refOpen
  if (refOpen !== undefined && refOpen.triggerRefOpenData !== undefined) {
    const triggerRefOpenData = refOpen.triggerRefOpenData
    console.debug('triggerRefOpenData', triggerRefOpenData)
    const activeTriggerReturn = triggerRefOpenData.activeTriggerReturn
    const returnUrlKey = activeTriggerReturn.returnUrlKey
    const paramObj = {}
    paramObj.S_DY_PARAM = activeTriggerReturn.refReturnUrlParam.S_DY_PARAM
    _thisObj.dealApi[returnUrlKey] = activeTriggerReturn.refReturnUrl
    _thisObj.dealParam[returnUrlKey] = paramObj
    const remoteUrlParam = getRemoteUrlParam(_thisObj, returnUrlKey, globalData)
    console.log('remote url param', remoteUrlParam)
    // const verify = getCommonRemoteUrlVerify(_thisObj, urlKey, postParam)
    // if (verify === 1) {
    //   // 查询验证未通过
    //   return
    // }
    // if (paramObj.S_DY_PARAM === undefined || paramObj.S_DY_PARAM.length === 0) {
    //   remoteUrlParam.item = returnItem
    // }
    remoteUrlParam.item = returnItem
    _thisObj.loading = true
    submitDealReq(remoteUrlParam).then((res) => {
      _thisObj.loading = false
      if (res.data.success) {
        _thisObj.$message.success(res.data.message)
        const modalKey = 'remoteData'
        _thisObj.reloadLoadData(formItem, res.data.data, modalKey, remoteUrlParam)
      } else {
        _thisObj.$message.warning(res.data.message)
      }
    })
  }
}

export function getThisObjSetValItem(thisObj, globalData, openParam, refSetVal) {
  const item = []
  let selectionRows = []
  if (globalData.tableSelectedRow !== undefined) {
    selectionRows = globalData.tableSelectedRow
  }
  for (let idx = 0; idx < selectionRows.length; idx++) {
    const row = selectionRows[idx]
    const mergeRow = Object.assign({}, globalData.globalParam, row)
    globalData.globalParam = mergeRow
    let record = Object.assign({})
    if (undefined !== refSetVal) {
      record = getNewCommonUrlParam(thisObj, globalData, mergeRow, refSetVal)
      // record = getThisObjCommonDealParam(thisObj, {}, globalData, mergeRow, refSetVal)
    } else {
      record = Object.assign({}, row)
    }
    item.push(record)
  }
  return item
}

export function evalEl(el, record) {
  if (undefined === el || el === '' || el === null) {
    return true
  }
  if (undefined === record || record === '' || record === null) {
    return false
  }
  const code = `function code(record){return ` + el + `}`
  const fun = new Function(`return ${code}`)()
  const funResult = fun(record)
  return funResult
}

/**
 * 表达式变量
 * @param elKey
 * @param elKeyInVal
 * @param record
 * @returns {boolean}
 */
export function evalElKeyInVal(elKey, elKeyInVal, record) {
  if (undefined === elKey || elKey === '' || elKey === null) {
    return true
  }
  if (undefined === elKeyInVal || elKeyInVal === '' || elKeyInVal === null) {
    return true
  }
  console.log(elKey, 'elKeyObj', elKeyObj, record)
  const elKeyObj = record[elKey]
  if (elKeyObj === undefined) {
    return true
  }

  if (elKeyObj instanceof Array) {
    for (const elKeyIdx in elKeyObj) {
      const elKeyVal = elKeyObj[elKeyIdx]
      if (elKeyInVal === elKeyVal) {
        return true
      }
    }
  } else {
    const elKeyObjArr = elKeyObj.split(',')
    for (const elKeyIdx in elKeyObjArr) {
      const elKeyVal = elKeyObjArr[elKeyIdx]
      if (elKeyInVal === elKeyVal) {
        return true
      }
    }
  }
  return false
}

export function getFormData(thisFormObj) {
  return thisFormObj
  // return thisFormObj.getFieldsValue()
}

/** *
 * el表达式执行结果
 */
export function processEl(record, objEl) {
  const code = `function code(record){return ` + objEl + `}`
  const fun = new Function(`return ${code}`)()
  const funResult = fun(record)
  return funResult
}

/**
 * 计算表达式的值
  */
export function evil(fnEl) {
  return new Function('return ' + fnEl)()
}

export function getDefaultOpenVal(thisObj) {
  const refSetOpenVal = []
  if (thisObj.initUiVal.columnsList !== undefined) {
    const columnsList = thisObj.initUiVal.columnsList.column
    for (const i in columnsList) {
      const column = columnsList[i]
      const key = column.dataIndex
      if (key !== 'action') {
        const obj = {}
        obj.key = key
        obj.val = key
        refSetOpenVal.push(obj)
      }
    }
  }
  const formKey = thisObj.initUiVal[thisObj.initFormKey].formKey
  for (const i in formKey) {
    const col = formKey[i].key
    const obj = {}
    obj.key = col
    obj.val = col
    refSetOpenVal.push(obj)
  }
  const openParamTmp = thisObj.openParam
  for (const tmpKey in openParamTmp) {
    const obj = {}
    obj.key = tmpKey
    obj.val = tmpKey
    refSetOpenVal.push(obj)
  }
  return refSetOpenVal
}

export function listToKeyData(list, key) {
  const data = {}
  const listLength = list.length
  for (let i = 0; i < listLength; i++) {
    const d = list[i]
    const k = d[key]
    data[k] = 1
  }
  return data
}

export function sortKey(array, key) {
  return array.sort(function(a, b) {
    const x = a[key]
    const y = b[key]
    return ((x < y) ? -1 : (x > y) ? 1 : 0)
  })
}

export function getFnObjData(thisObj, dataList, globalData, elTrueOrFlag) {
  let tmpObj = {}
  if (dataList === undefined || dataList.length === 0) {
    // 没配置时,显示返回true
    // tmpObj[key] = elTrueOrFlag
    tmpObj.elKey = elTrueOrFlag
  } else {
    const tmpArr = getProcessElTrueList(thisObj, dataList, globalData)
    if (tmpArr.length > 0) {
      tmpObj = tmpArr[0]
      tmpObj.elKey = elTrueOrFlag
      // tmpObj[key] = elTrueOrFlag
    } else {
      tmpObj.elKey = !elTrueOrFlag
      // tmpObj[key] = !elTrueOrFlag
    }
  }
  return tmpObj
}
/**
 * @param thisObj 当前对象
 * @param key 变量
 * @param dataList 数据集
 * @param param 界面参数
 * @param elTrueOrFlag 满足条件时，返回true或给key 赋值true或false
 * @returns {{}}
 */
export function getProcessElTrueData(thisObj, key, dataList, globalData, elTrueOrFlag) {
  const tmpObj = {}
  if (dataList === undefined || dataList.length === 0) {
    // 没配置时,显示返回true
    tmpObj[key] = elTrueOrFlag
  } else {
    const tmpArr = getProcessElTrueList(thisObj, dataList, globalData)
    if (tmpArr.length > 0) {
      tmpObj[key] = elTrueOrFlag
    } else {
      tmpObj[key] = !elTrueOrFlag
    }
  }
  return tmpObj
}
export function getProcessElTrueList(thisObj, dataList, globalData) {
  const tmpArr = []
  for (const keyIdx in dataList) {
    const tmpData = dataList[keyIdx]
    if (undefined === tmpData.objEl) {
      tmpArr.push(tmpData)
      break
    } else {
      const elFlag = processEl(globalData.globalParam, tmpData.objEl)
      if (elFlag) {
        tmpArr.push(tmpData)
        break
      }
    }
  }
  return tmpArr
}

// export function fetchExportData(thisObj, urlKey, params = {}, refExport = {}) {
//   const formKeyData = getFormModelKeyData(thisObj)
//   const record = Object.assign({}, thisObj.openParam, thisObj.initData, formKeyData)
//   const urlData = {}
//   urlData.url = '/run/ctr/submitJson'
//   urlData.S_PAGE_ID = refExport.refExportObjPageId
//   urlData.S_PAGE_VER = refExport.refExportObjPageVer
//   urlData.S_PARTITION = refExport.refExportObjPartition
//   const urlParamKey = refExport.refExportObjUrlParam
//   const url = getRemoteUrlPathInitData(thisObj, urlKey, urlData)
//   const urlParam = getCommonRemoteUrlParam(urlParamKey, record)
//   const postParam = Object.assign({}, urlParam, url, params)
//   thisObj.loading = true
//   submitDealReq(postParam).then((res) => {
//     if (res.data.success) {
//       const expData = res.data.data
//       console.log('返回数据:', expData)
//       const url = '/autocode/file/ctr/export/' + expData.S_ID
//       request.download(url, {}, expData.S_FILE_NAME)
//       thisObj.loading = false
//     } else {
//       thisObj.$message.warning(res.data.message)
//     }
//   }).catch(reason => {
//     console.log('reason' + reason)
//   })
// }
//
// export function getDealParam(thisObj, dealKey, record) {
//   if (dealKey === 'page') {
//     const iPageNo = thisObj.tablePagination.current
//     const iPageSize = thisObj.tablePagination.pageSize
//     thisObj.tableQueryParam.iPageNo = iPageNo
//     thisObj.tableQueryParam.iPageSize = iPageSize
//   }
//   const postParam = getDealSubmitParam(thisObj, dealKey, record, thisObj.dealApi, thisObj.dealParam, thisObj.paramData, thisObj.tableQueryParam)
//   return postParam
// }
